<?php

namespace app\index\controller;

use think\Controller;
use think\Request;
use think\Db;

class IndexController extends Controller
{
    public function _initialize()
    {

        $request = Request::instance();
        $controller = $request->controller();   // 获取访问的控制器名
        $action = $request->action();           // 获取访问的方法名
        $unode = $controller.' '.$action;



        //判断是否登陆
        if(!session('data.username')){
            $this->error('请先登录','index/index/login');
        }

        //判断权限 admin拥有所有权限
        if(session('data.username') != 'admin') {
            $node = session('usernode');
            if (!in_array(strtolower($unode), $node)) {
                $this->error('您没有访问权限');
            }
        }


        //已发送消息的标题内容时间
        $read = DB::view('message', ['session', 'title', 'id','time'])
            ->order('time','desc')
            ->limit('0,4')
            ->select();

        //查询未读消息条数
        $unread = DB('mes_bus')
            ->where([
                'status'=>'2'
            ])
            ->count('sid');

        //已发消息数量
        $summes = DB('mes_bus')
            ->count('sid');

        foreach($read as $k=>$v){
            $title[]=$v['title'];
            $time[]=$v['time'];
            $mes[]=$v['session'];
            $id[$k]=$v['id'];

            //查询当前消息总条数
            $this_read[] = DB('mes_bus')
                ->where([
                    'sid'=>$id[$k]
                ])
                ->count('sid');

            //查询当前消息已读情况
            $this_onread[] = DB('mes_bus')
                ->where([
                    'status'=>'1',
                    'sid'=>$id[$k]
                ])
                ->count('sid');
        }

//        session('data',$res[0]);
//        session('usernode',$node['unode']);
        session('summes',$summes);
        session('unread',$unread);
//        session('res',$read);
        session('time',$time);
        session('title',$title);
        session('mes',$mes);
        session('this_read',$this_read);
        session('this_onread',$this_onread);

    }

}
